package edu.gatech.gro.model.parser;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import edu.gatech.gro.model.ListGroup;

public class ListGroupListItemJsonHandler extends JsonHandler {

	private static final String TAG = "LIST_GROUP_LIST_ITEM_JSON_HANDLER";

	@Override
	protected void parseDataArray() {
		try {
			getResponse().setData(json.getJSONArray("data"));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
	}

	@Override
	protected void parseData() {
		ListGroup dataParsed = null;
		try {
			dataParsed = getListGroup(json.getJSONObject("data"));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		getResponse().setData(dataParsed);
	}

	public static ArrayList<ListGroup> getListGroups(JSONArray array) {
		ArrayList<ListGroup> dataParsed = new ArrayList<ListGroup>();
		if (array != null) {
			try {
				for (int i = 0; i < array.length(); i++) {
					dataParsed.add(getListGroup(array.getJSONObject(i)));
				}
			} catch (JSONException e) {
				Log.e(TAG, e.getMessage());
			}
		}
		return dataParsed;
	}

	public static ListGroup getListGroup(JSONObject obj) {
		ListGroup group = new ListGroup();
		try {
			group.setId(obj.getInt("id"));
			group.setName(obj.getString("name"));
			group.setNameClean(obj.getString("nameClean"));
			if (obj.has("items") && obj.optJSONArray("items") != null) {
				group.setItems(ListItemJsonHandler.getListItems(obj.getJSONArray("items")));
			}
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		return group;
	}
}
